/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.grouporders.service;

import java.math.BigDecimal;
import java.util.*;

import com.github.wxpay.sdk.WXPayUtil;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.IdGen;
import com.jeeplus.common.utils.SnowFlake;
import com.jeeplus.common.utils.WechatUtil;
import com.jeeplus.modules.account.entity.Account;
import com.jeeplus.modules.account.mapper.AccountMapper;
import com.jeeplus.modules.address.entity.Address;
import com.jeeplus.modules.address.mapper.AddressMapper;
import com.jeeplus.modules.dynamicrecord.entity.DynamicRecord;
import com.jeeplus.modules.dynamicrecord.mapper.DynamicRecordMapper;
import com.jeeplus.modules.dynamicrecord.service.DynamicRecordService;
import com.jeeplus.modules.grouprecord.entity.GroupRecord;
import com.jeeplus.modules.grouprecord.mapper.GroupRecordMapper;
import com.jeeplus.modules.groupreturn.entity.GroupReturn;
import com.jeeplus.modules.groupreturn.mapper.GroupReturnMapper;
import com.jeeplus.modules.member.entity.Member;
import com.jeeplus.modules.member.mapper.MemberMapper;
import com.jeeplus.modules.ordersstore.entity.OrdersStore;
import com.jeeplus.modules.ordersstore.service.OrdersStoreService;
import com.jeeplus.modules.partitioninfo.entity.PartitionInfo;
import com.jeeplus.modules.partitioninfo.mapper.PartitionInfoMapper;
import com.jeeplus.modules.recharge.entity.Recharge;
import com.jeeplus.modules.recharge.service.RechargeService;
import com.jeeplus.modules.sessions.entity.Sessions;
import com.jeeplus.modules.sessions.mapper.SessionsMapper;
import com.jeeplus.modules.sessions.service.SessionsService;
import com.jeeplus.modules.teamrecord.entity.TeamRecord;
import com.jeeplus.modules.wxgroup.entity.WxGroup;
import com.jeeplus.modules.wxgroup.mapper.WxGroupMapper;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.service.CrudService;
import com.jeeplus.modules.grouporders.entity.GroupOrders;
import com.jeeplus.modules.grouporders.mapper.GroupOrdersMapper;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拼团订单Service
 * @author w
 * @version 2021-01-26
 */
@Service
@Transactional(readOnly = true)
public class GroupOrdersService extends CrudService<GroupOrdersMapper, GroupOrders> {
	@Autowired
	private GroupRecordMapper groupRecordMapper;
	@Autowired
	private SessionsMapper sessionsMapper;
	@Autowired
	private AccountMapper accountMapper;
	@Autowired
	private MemberMapper memberMapper;
	@Autowired
	private AddressMapper addressMapper;
	@Autowired
	private PartitionInfoMapper partitionInfoMapper;
	@Autowired
	private DynamicRecordMapper dynamicRecordMapper;
	@Autowired
	private GroupReturnMapper groupReturnMapper;
	@Autowired
	private WxGroupMapper wxGroupMapper;
	@Autowired
	private OrdersStoreService ordersStoreService;
	@Autowired
	private RechargeService rechargeService;
	@Autowired
	private DynamicRecordService dynamicRecordService;

	private final static String APPID = "wxf8333f0015bfad41";
	private final static String APPSECRET = "8104ad1318a445ace1bf2eb604330783";
	private final static String MCH_ID = "1607079032";
	private final static String PATERNERKEY = "yizhelegouyizhelegou111111686868";

	private org.slf4j.Logger logger = LoggerFactory.getLogger(getClass());


	public GroupOrders get(String id) {
		return super.get(id);
	}
	
	public List<GroupOrders> findList(GroupOrders groupOrders) {
		return super.findList(groupOrders);
	}
	
	public Page<GroupOrders> findPage(Page<GroupOrders> page, GroupOrders groupOrders) {
		return super.findPage(page, groupOrders);
	}
	
	@Transactional(readOnly = false)
	public void save(GroupOrders groupOrders) {
		super.save(groupOrders);
	}
	
	@Transactional(readOnly = false)
	public void delete(GroupOrders groupOrders) {
		super.delete(groupOrders);
	}

	/**
	 * 参与拼团
	 * @param sessionsId
	 * @param member
	 * @param recordId
	 * @return
	 */
	@Transactional(readOnly = false)
	public AjaxJson participateInTheCompetition(String sessionsId, Member member, String recordId, String method, String openid, HttpServletRequest request, HttpServletResponse response) {
		AjaxJson aj = new AjaxJson();
		String orderNo = "";
		//查询往前记录，创建新的拼团记录1、第一次开团
		//开团之前的最新记录
		GroupRecord latestRecord = groupRecordMapper.findLatestRecord(sessionsId);
		//查询拼团记录订单数
//		GroupOrders sOrders = new GroupOrders();
//		sOrders.setGroupRecord(latestRecord);
//		sOrders.setMember(member);
//		List<GroupOrders> sList1 = findList(sOrders);
//		if (sList1.size()>0 && "0".equals(latestRecord.getIsEnd())){
//			aj.setSuccess(false);
//			aj.setMsg("请耐心等待开奖");
//			return aj;
//		}
		//查询拼团记录订单数
//		GroupOrders selectOrders = new GroupOrders();
//		selectOrders.setGroupRecord(latestRecord);
//		List<GroupOrders> sList = findList(selectOrders);
		//查询场次
		Sessions sessions = sessionsMapper.get(sessionsId);
		//场次参与金额
		BigDecimal money = BigDecimal.valueOf(sessions.getSessionsPrice());
		if ("0".equals(method)){
			//获取用户余额
			Account account = accountMapper.get(member.getAccount().getId());
			if (account != null){
				BigDecimal balance = BigDecimal.valueOf(account.getYue());
				if (balance.compareTo(money) == 1 || balance.compareTo(money) == 0){
					SnowFlake snowFlake = new SnowFlake(2, 3);
					//生成订单编号
					Long orderFormNumber = snowFlake.nextId();
					if (latestRecord == null){
						logger.debug("================================11111,sessionId:"+sessionsId);
						orderNo = orderFormNumber.toString();
						//首次拼团，创建第一期记录
						GroupRecord groupRecord = new GroupRecord();
						groupRecord.setId(IdGen.uuid());
						groupRecord.setPercentNo(1);
						groupRecord.setSessions(sessions);
						groupRecord.setIsEnd("0");
						groupRecord.setOrderNo(orderNo);
						groupRecord.setPrizeStatus("0");
						groupRecord.setGroupStatus("0");
						groupRecord.preInsert();
						groupRecordMapper.insert(groupRecord);
						//扣除场次参与金额
						account.setYue(balance.subtract(money).doubleValue());
						account.preUpdate();
						accountMapper.update(account);
						//扣除能量值  -1
						PartitionInfo partitionInfo = new PartitionInfo();
						partitionInfo.setMember(member);
						partitionInfo.setSessions(sessions);
						List<PartitionInfo> partitionInfoList = partitionInfoMapper.findList(partitionInfo);
						if (partitionInfoList.size() > 0){
							partitionInfoList.get(0).setEnergyValue(partitionInfoList.get(0).getEnergyValue()-1);
							partitionInfoList.get(0).preUpdate();
							partitionInfoMapper.update(partitionInfoList.get(0));
						}
						//购买拼团订单
						GroupOrders groupOrders = new GroupOrders();
						groupOrders.setGroupRecord(groupRecord);
						groupOrders.setMember(member);
						groupOrders.setOrderNo(orderNo);
						groupOrders.setMoney(money.doubleValue());
						//未开奖
						groupOrders.setOrderStatus("0");
						save(groupOrders);

						aj.setMsg("参与成功,请等待拼团成功后开奖。");
						aj.put("orderNo",orderNo);
					}else {
						//查询当前场次所有未成团记录
						GroupRecord entity = new GroupRecord();
						entity.setSessions(sessions);
//						entity.setGroupStatus("0");
//						entity.setIsEnd("0");
						List<GroupRecord> nonList = groupRecordMapper.findNonList(entity);
						//记录扫描过得未成团记录
						List<GroupRecord> scanList = new ArrayList<>();
						if (nonList.size()>0){
							for (GroupRecord groupRecord : nonList) {
								GroupOrders selectOrders = new GroupOrders();
								selectOrders.setGroupRecord(groupRecord);
								List<GroupOrders> sList = findList(selectOrders);
								if (sList.stream().anyMatch(groupOrders -> groupOrders.getMember().getId().equals(member.getId()))){
									scanList.add(groupRecord);
									continue;
								}else {
									orderNo = groupRecord.getOrderNo();
									//扣除场次参与金额
									account.setYue(balance.subtract(money).doubleValue());
									account.preUpdate();
									accountMapper.update(account);
									//扣除能量值  -1
									PartitionInfo partitionInfo = new PartitionInfo();
									partitionInfo.setMember(member);
									partitionInfo.setSessions(sessions);
									List<PartitionInfo> partitionInfoList = partitionInfoMapper.findList(partitionInfo);
									if (partitionInfoList.size() > 0){
										partitionInfoList.get(0).setEnergyValue(partitionInfoList.get(0).getEnergyValue()-1);
										partitionInfoList.get(0).preUpdate();
										partitionInfoMapper.update(partitionInfoList.get(0));
									}
									//购买拼团订单
									GroupOrders groupOrders = new GroupOrders();
									groupOrders.setGroupRecord(groupRecord);
									groupOrders.setMember(member);
									groupOrders.setOrderNo(groupRecord.getOrderNo());
									//未开奖
									groupOrders.setOrderStatus("0");
									groupOrders.setMoney(money.doubleValue());
									save(groupOrders);
									//成团
									if (sList.size()+1 == sessions.getSessionsMember()){
										//成团
										groupRecord.setGroupStatus("1");
										groupRecord.setGroupDate(new Date());
										groupRecord.preUpdate();
										groupRecordMapper.update(groupRecord);
										//开奖
										drawPrize(groupRecord);
									}
									aj.setMsg("参与成功,请等待开奖。");
									aj.put("orderNo",orderNo);
									break;
								}
							}
							//未成团记录全部扫描完，若用户都已参与，让用户开启一个新的团
							if (scanList.size() == nonList.size()){
								orderNo = orderFormNumber.toString();
								//   创建新一期的拼团记录
								GroupRecord groupRecord = new GroupRecord();
								groupRecord.setId(IdGen.uuid());
								groupRecord.setPercentNo(latestRecord.getPercentNo()+1);
								groupRecord.setSessions(sessions);
								groupRecord.setIsEnd("0");
								groupRecord.setOrderNo(orderNo);
								groupRecord.setPrizeStatus("0");
								groupRecord.setGroupStatus("0");
								groupRecord.preInsert();
								groupRecordMapper.insert(groupRecord);
								//扣除场次参与金额
								account.setYue(balance.subtract(money).doubleValue());
								account.preUpdate();
								accountMapper.update(account);
								//扣除能量值  -1
								PartitionInfo partitionInfo = new PartitionInfo();
								partitionInfo.setMember(member);
								partitionInfo.setSessions(sessions);
								List<PartitionInfo> partitionInfoList = partitionInfoMapper.findList(partitionInfo);
								if (partitionInfoList.size() > 0){
									partitionInfoList.get(0).setEnergyValue(partitionInfoList.get(0).getEnergyValue()-1);
									partitionInfoList.get(0).preUpdate();
									partitionInfoMapper.update(partitionInfoList.get(0));
								}
								//购买拼团订单
								GroupOrders groupOrders = new GroupOrders();
								groupOrders.setGroupRecord(groupRecord);
								groupOrders.setMember(member);
								groupOrders.setOrderNo(orderNo);
								//未开奖
								groupOrders.setOrderStatus("0");
								groupOrders.setMoney(money.doubleValue());
								save(groupOrders);
								aj.setMsg("参与成功,请等待拼团成功后开奖。");
								aj.put("orderNo",orderNo);
							}
						}else {
							orderNo = orderFormNumber.toString();
							//已成团   创建新一期的拼团记录
							GroupRecord groupRecord = new GroupRecord();
							groupRecord.setId(IdGen.uuid());
							groupRecord.setPercentNo(latestRecord.getPercentNo()+1);
							groupRecord.setSessions(sessions);
							groupRecord.setIsEnd("0");
							groupRecord.setOrderNo(orderNo);
							groupRecord.setPrizeStatus("0");
							groupRecord.setGroupStatus("0");
							groupRecord.preInsert();
							groupRecordMapper.insert(groupRecord);
							//扣除场次参与金额
							account.setYue(balance.subtract(money).doubleValue());
							account.preUpdate();
							accountMapper.update(account);
							//扣除能量值  -1
							PartitionInfo partitionInfo = new PartitionInfo();
							partitionInfo.setMember(member);
							partitionInfo.setSessions(sessions);
							List<PartitionInfo> partitionInfoList = partitionInfoMapper.findList(partitionInfo);
							if (partitionInfoList.size() > 0){
								partitionInfoList.get(0).setEnergyValue(partitionInfoList.get(0).getEnergyValue()-1);
								partitionInfoList.get(0).preUpdate();
								partitionInfoMapper.update(partitionInfoList.get(0));
							}
							//购买拼团订单
							GroupOrders groupOrders = new GroupOrders();
							groupOrders.setGroupRecord(groupRecord);
							groupOrders.setMember(member);
							groupOrders.setOrderNo(orderNo);
							//未开奖
							groupOrders.setOrderStatus("0");
							groupOrders.setMoney(money.doubleValue());
							save(groupOrders);
							aj.setMsg("参与成功,请等待拼团成功后开奖。");
							aj.put("orderNo",orderNo);
						}
					}
				}else {
					aj.setSuccess(false);
					aj.setMsg("余额不足，请及时充值");
				}

			}else {
				aj.setSuccess(false);
				aj.setMsg("账户信息有误，请联系管理员");
			}
		}else if ("1".equals(method)){
			SnowFlake snowFlake = new SnowFlake(2, 3);
			//生成订单编号
			Long orderFormNumber = snowFlake.nextId();
			orderNo = orderFormNumber.toString();

			BigDecimal bd = money.multiply(BigDecimal.valueOf(100)).setScale(0,BigDecimal.ROUND_HALF_DOWN);
			try {
				String nonce_str = WXPayUtil.generateNonceStr();
				String body = "乐购商城-"+orderNo;
				String notify_url = "http://lgshangcheng.com/ptw/f/group/callBack";
				Map<String, String> paraMap = new HashMap<String, String>();
				// 获取请求ip地址
				String ip = request.getHeader("x-forwarded-for");
				if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
					ip = request.getHeader("Proxy-Client-IP");
				}
				if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
					ip = request.getHeader("WL-Proxy-Client-IP");
				}
				if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
					ip = request.getRemoteAddr();
				}
				if (ip.indexOf(",") != -1) {
					String[] ips = ip.split(",");
					ip = ips[0].trim();
				}

				paraMap.put("appid", APPID);
				paraMap.put("body", body);
				paraMap.put("mch_id", MCH_ID);
				paraMap.put("nonce_str", nonce_str);
				paraMap.put("out_trade_no", orderNo);// 订单号
				paraMap.put("spbill_create_ip", ip);
				paraMap.put("total_fee",  bd+ "");
				paraMap.put("notify_url", notify_url);
				paraMap.put("openid", openid);
				paraMap.put("trade_type", "JSAPI");

				System.out.println();
				System.out.println("appid=" + paraMap.get("appid"));
				System.out.println("mch_id=" + paraMap.get("mch_id"));
				System.out.println("body=" + paraMap.get("body"));
				System.out.println("nonce_str=" + paraMap.get("nonce_str"));
				System.out.println("openid=" + paraMap.get("openid"));
				System.out.println("out_trade_no=" + paraMap.get("out_trade_no"));
				System.out.println("spbill_create_ip=" + paraMap.get("spbill_create_ip"));
				System.out.println("total_fee=" + paraMap.get("total_fee"));
				System.out.println("trade_type=" + paraMap.get("trade_type"));
				System.out.println("notify_url=" + paraMap.get("notify_url"));
//                        System.out.println("sign_type=" + paraMap.get("sign_type"));
				String sign = WXPayUtil.generateSignature(paraMap, PATERNERKEY);
				paraMap.put("sign", sign);
				System.out.println("下单签名=" + sign);
				System.out.println("paraMap="+paraMap);
				String xml = WXPayUtil.mapToXml(paraMap);// 将所有参数(map)转xml格式
				// 统一下单 https://api.mch.weixin.qq.com/pay/unifiedorder
				String unifiedorder_url = "https://api.mch.weixin.qq.com/pay/unifiedorder";

				System.out.println("签名参数==============="+xml);
//                        String xmlStr = HttpUtils.sendPost(unifiedorder_url, xml);// 发送post请求"统一下单接口"返回预支付id:prepay_id
				String xmlStr = WechatUtil.requestOnce(unifiedorder_url, xml);
				System.out.println("返回xml===" + xmlStr);

				if (xmlStr.indexOf("SUCCESS") != -1) {

					WxGroup wxGroup = new WxGroup();
					wxGroup.setOrderNo(orderNo);
					wxGroup.setCost(money.doubleValue());
					wxGroup.setMemberId(member.getId());
					wxGroup.setSessionsId(sessionsId);
					wxGroup.setId(IdGen.uuid());
					wxGroup.preInsert();
					wxGroup.setIsNewRecord(true);
					wxGroupMapper.insert(wxGroup);


					Map<String, String> map = WXPayUtil.xmlToMap(xmlStr);
					String prepay_id = (String) map.get("prepay_id");
					Map<String, String> payMap = new HashMap<String, String>();
					payMap.put("appId", APPID);
					payMap.put("timeStamp", System.currentTimeMillis()/1000 + "");
					payMap.put("nonceStr", WXPayUtil.generateNonceStr());
					payMap.put("signType", "MD5");
					payMap.put("package", "prepay_id=" + prepay_id);
					System.out.println("timeStamp=" + payMap.get("timeStamp"));
					System.out.println("nonceStr=" + payMap.get("nonceStr"));
					System.out.println("signType=" + "MD5");
					System.out.println("package=" + payMap.get("package"));
					System.out.println("预支付id=" + prepay_id);
					String paySign = WXPayUtil.generateSignature(payMap, PATERNERKEY);
					payMap.put("paySign", paySign);
					payMap.put("prepay_id", payMap.get("package"));
					System.out.println("=============================================payMap:"+payMap);
					aj.put("payMap",payMap);
					aj.setSuccess(true);
				}else {
					aj.setSuccess(false);
					aj.setMsg("支付失败");
				}
			} catch (Exception e) {
				e.printStackTrace();
				aj.setSuccess(false);
				aj.setMsg("支付失败");
				System.out.println("错误！错误！错误！");
			}
		}

		return aj;
	}

	@Transactional(readOnly = false)
	public void drawPrize(GroupRecord groupRecord) {
		//查询本期拼团订单
//		GroupOrders groupOrders = new GroupOrders();
//		groupOrders.setGroupRecord(latestRecord);
//		List<GroupOrders> list = findList(groupOrders);
//		//随机选中一位中奖用户
//		int random = (int) (Math.random()*(list.size()-1));
//		for (int i = 0; i < list.size(); i++) {
//			//未中奖
//			list.get(i).setPrizeFlag("0");
//			//返利
//			Member m = memberMapper.get(list.get(i).getMember().getId());
//			Account a = accountMapper.get(m.getAccount().getId());
//			//返利金额
//			BigDecimal back = BigDecimal.valueOf(list.get(i).getMoney()).multiply(BigDecimal.valueOf(sessions.getSessionsBack()).divide(BigDecimal.valueOf(100),2,BigDecimal.ROUND_HALF_DOWN));
//			a.setYue(a.getYue()+back.doubleValue());
//			a.preUpdate();
//			accountMapper.update(a);
//			//记录
//			GroupReturn groupReturn = new GroupReturn();
//			groupReturn.setId(IdGen.uuid());
//			groupReturn.setMember(m);
//			groupReturn.setMoney(back.doubleValue());
//			groupReturn.setOrderNo(list.get(i).getOrderNo());
//			groupReturn.setSessions(sessions);
//			groupReturn.setIsNewRecord(true);
//			groupReturn.preInsert();
//			groupReturnMapper.insert(groupReturn);
//			if (i == random){
//				//查询中奖用户收货地址
//				Address address = new Address();
//				address.setMember(list.get(i).getMember());
//				List<Address> addressList = addressMapper.findList(address);
//				//中奖
//				list.get(i).setPrizeFlag("1");
//				//未发货
//				list.get(i).setOrderStatus("0");
//				list.get(i).setAddress(addressList.get(0) == null?"":addressList.get(0).getAddress()+addressList.get(0).getDetail());
//				latestRecord.setMember(list.get(i).getMember());
//				//幸运星+1
//				PartitionInfo partitionInfo = new PartitionInfo();
//				partitionInfo.setMember(list.get(i).getMember());
//				partitionInfo.setSessions(latestRecord.getSessions());
//				List<PartitionInfo> partitionInfoList = partitionInfoMapper.findList(partitionInfo);
//				if (partitionInfoList.size() > 0){
//					partitionInfoList.get(0).setStars(partitionInfoList.get(0).getStars()+1);
//					partitionInfoList.get(0).preUpdate();
//					partitionInfoMapper.update(partitionInfoList.get(0));
//					//够五个发奖励
//					if (partitionInfoList.get(0).getStars() % 5 == 0){
//						Member member = memberMapper.get(list.get(i).getMember().getId());
//						Account account = accountMapper.get(member.getAccount().getId());
//						account.setYue(account.getYue()+(sessions.getStarProfit()*5));
//						account.preUpdate();
//						accountMapper.update(account);
//						//记录
//						DynamicRecord dynamicRecord = new DynamicRecord();
//						dynamicRecord.setId(IdGen.uuid());
//						dynamicRecord.setMember(list.get(i).getMember());
//						dynamicRecord.setFrommem(list.get(i).getMember());
//						dynamicRecord.setName("幸运收益");
//						dynamicRecord.setMoney(sessions.getStarProfit()*5);
//						dynamicRecord.setRemarks(sessions.getId());
//						dynamicRecord.preInsert();
//						dynamicRecordMapper.insert(dynamicRecord);
//					}
//
//				}
//			}
//			save(list.get(i));
//		}
//		latestRecord.setGroupStatus("1");
//		latestRecord.setPrizeStatus("1");
////		latestRecord.setIsEnd("1");
//		latestRecord.setGroupDate(new Date());
//		latestRecord.preUpdate();
//		groupRecordMapper.update(latestRecord);

		Sessions sessions = sessionsMapper.get(groupRecord.getSessions().getId());

		//查询本期拼团订单
		GroupOrders groupOrders = new GroupOrders();
		groupOrders.setGroupRecord(groupRecord);
		List<GroupOrders> ordersList = findList(groupOrders);
		//随机选中一位中奖用户
		int random = (int) (Math.random()*(ordersList.size()-1));
		int random1 = (int) (Math.random()*(ordersList.size()-1));
		while (random1 == random){
			random1 = (int) (Math.random()*(ordersList.size()-1));
		}
		for (int i = 0; i < ordersList.size(); i++) {
			Member m = memberMapper.get(ordersList.get(i).getMember().getId());
			Account a = accountMapper.get(m.getAccount().getId());
			//未中奖
			ordersList.get(i).setPrizeFlag("0");
			//所有订单已开奖
			ordersList.get(i).setOrderStatus("1");
			if (i == random || i == random1){
				//查询中奖用户收货地址
				Address address = new Address();
				address.setMember(ordersList.get(i).getMember());
				List<Address> addressList = addressMapper.findList(address);
				//中奖
				ordersList.get(i).setPrizeFlag("1");
				ordersList.get(i).setAddress(addressList.get(0) == null?"":addressList.get(0).getAddress()+addressList.get(0).getDetail());
				if (i == random){
					groupRecord.setMember(ordersList.get(i).getMember());
				}else if (i == random1){
					groupRecord.setSecondMember(ordersList.get(i).getMember());
				}

				//幸运星+1
				PartitionInfo partitionInfo = new PartitionInfo();
				partitionInfo.setMember(ordersList.get(i).getMember());
				partitionInfo.setSessions(groupRecord.getSessions());
				List<PartitionInfo> partitionInfoList = partitionInfoMapper.findList(partitionInfo);
				if (partitionInfoList.size() > 0){
					partitionInfoList.get(0).setIntegral((partitionInfoList.get(0).getIntegral() == null?0:partitionInfoList.get(0).getIntegral())+(sessions.getBonusPoints() == null?0:sessions.getBonusPoints()));
					partitionInfoList.get(0).preUpdate();
					partitionInfoMapper.update(partitionInfoList.get(0));
					//账户发放积分
					Member member = memberMapper.get(ordersList.get(i).getMember().getId());
					Account account = accountMapper.get(member.getAccount().getId());
					account.setIntegral((account.getIntegral()==null?0:account.getIntegral())+(sessions.getBonusPoints()==null?0:sessions.getBonusPoints()));
					account.preUpdate();
					accountMapper.update(account);
					//记录
					DynamicRecord dynamicRecord = new DynamicRecord();
					dynamicRecord.setId(IdGen.uuid());
					dynamicRecord.setMember(ordersList.get(i).getMember());
					dynamicRecord.setFrommem(ordersList.get(i).getMember());
					dynamicRecord.setName("幸运收益");
					dynamicRecord.setMoney(sessions.getBonusPoints());
					dynamicRecord.setRemarks(sessions.getId());
					dynamicRecord.preInsert();
					dynamicRecordMapper.insert(dynamicRecord);

				}
				//发放团队奖
				awardTeamAward(m,BigDecimal.valueOf(sessions.getSessionsPrice()));
			}else {
				//返利
				//返利金额
				BigDecimal back = BigDecimal.valueOf(ordersList.get(i).getMoney()).multiply(BigDecimal.valueOf(sessions.getSessionsBack()).divide(BigDecimal.valueOf(100),2,BigDecimal.ROUND_HALF_DOWN));
				a.setYue(a.getYue()+back.doubleValue());
				a.preUpdate();
				accountMapper.update(a);
				//记录
				GroupReturn groupReturn = new GroupReturn();
				groupReturn.setId(IdGen.uuid());
				groupReturn.setMember(m);
				groupReturn.setMoney(back.doubleValue());
				groupReturn.setOrderNo(ordersList.get(i).getOrderNo());
				groupReturn.setSessions(sessions);
				groupReturn.setIsNewRecord(true);
				groupReturn.preInsert();
				groupReturnMapper.insert(groupReturn);
				//处理团队奖励相关事务  ---- 不中奖的返
				manageTeam(m,BigDecimal.valueOf(ordersList.get(i).getMoney()),sessions);
			}
			save(ordersList.get(i));
		}
		//已开奖
		groupRecord.setPrizeStatus("1");
		//结束
		groupRecord.setIsEnd("1");
		groupRecord.preUpdate();
		groupRecordMapper.update(groupRecord);
	}

	@Transactional(readOnly = false)
	public void manageTeam(Member member,BigDecimal money,Sessions sessions) {
		//给上级添加业绩
		//团队业绩   活跃值
		if (member.getP() != null){
			Member pMember = memberMapper.get(member.getP().getId());
			if (pMember != null){
				while (pMember != null){
					Account account = accountMapper.get(pMember.getAccount().getId());
					account.setTeam(BigDecimal.valueOf(account.getTeam()).add(money).doubleValue());
					accountMapper.update(account);
					if (pMember.getP() != null){
						pMember = memberMapper.get(pMember.getP().getId());
					}else {
						break;
					}
				}
			}
		}

		//	直推间推
		if (member.getP() != null){
			Member upMem = memberMapper.get(member.getP().getId());
			if (upMem != null && !"admin".equals(upMem.getLoginName())){
				//查询用户是否参与过拼团---有效会员
				GroupOrders groupOrders = new GroupOrders();
				groupOrders.setMember(upMem);
				List<GroupOrders> list = findList(groupOrders);
				if (list.size()>0){
					//处理账户收益明细及积分

					BigDecimal recordMoney = money.multiply((BigDecimal.valueOf(sessions.getSessionsBack()).subtract(BigDecimal.valueOf(100))).divide(BigDecimal.valueOf(100),2,BigDecimal.ROUND_HALF_DOWN)).multiply(BigDecimal.valueOf(0.1));
//		                BigDecimal integral = money.multiply(BigDecimal.valueOf(0.08)).multiply(BigDecimal.valueOf(0.02));
					Account account = accountMapper.get(upMem.getAccount().getId());
					//余额
					account.setYue(recordMoney.add(BigDecimal.valueOf(account.getYue())).doubleValue());
					//dynamicProfit   总动态收益
					account.setDynamicProfit(recordMoney.add(BigDecimal.valueOf(account.getDynamicProfit())).doubleValue());
					//todayDynamic    今日动态收益
					account.setTodayDynamic(recordMoney.add(BigDecimal.valueOf(account.getTodayDynamic())).doubleValue());
					//totalProfit     总收益
					account.setTotalProfit(recordMoney.add(BigDecimal.valueOf(account.getTotalProfit())).doubleValue());
					//todayProfit     今日总收益
					account.setTodayProfit(recordMoney.add(BigDecimal.valueOf(account.getTodayProfit())).doubleValue());
					//integral   积分
//		                account.setIntegral(integral.add(BigDecimal.valueOf(account.getIntegral())).doubleValue());
					accountMapper.update(account);
					//插入收益记录
					DynamicRecord dynamicRecord = new DynamicRecord();
					dynamicRecord.setId(IdGen.uuid());
					dynamicRecord.preInsert();
					dynamicRecord.setFrommem(member);
					dynamicRecord.setMember(upMem);
					dynamicRecord.setMoney(recordMoney.doubleValue());
					dynamicRecord.setName("推荐奖(直推)");
					dynamicRecordMapper.insert(dynamicRecord);
				}

				if (upMem.getP() != null){
					upMem = memberMapper.get(upMem.getP().getId());
					if (upMem != null  && !"admin".equals(upMem.getLoginName())){
						GroupOrders groupOrders1 = new GroupOrders();
						groupOrders1.setMember(upMem);
						List<GroupOrders> list1 = findList(groupOrders1);
						if (list1.size()>0){
							//处理账户收益明细及积分
							BigDecimal recordMoney1 = money.multiply((BigDecimal.valueOf(sessions.getSessionsBack()).subtract(BigDecimal.valueOf(100))).divide(BigDecimal.valueOf(100),2,BigDecimal.ROUND_HALF_DOWN)).multiply(BigDecimal.valueOf(0.2));
//		                        BigDecimal integral1 = money.multiply(BigDecimal.valueOf(0.005)).multiply(BigDecimal.valueOf(0.02));
							Account account1 = accountMapper.get(upMem.getAccount().getId());
							//余额
							account1.setYue(recordMoney1.add(BigDecimal.valueOf(account1.getYue())).doubleValue());
							//dynamicProfit   总动态收益
							account1.setDynamicProfit(recordMoney1.add(BigDecimal.valueOf(account1.getDynamicProfit())).doubleValue());
							//todayDynamic    今日动态收益
							account1.setTodayDynamic(recordMoney1.add(BigDecimal.valueOf(account1.getTodayDynamic())).doubleValue());
							//totalProfit     总收益
							account1.setTotalProfit(recordMoney1.add(BigDecimal.valueOf(account1.getTotalProfit())).doubleValue());
							//todayProfit     今日总收益
							account1.setTodayProfit(recordMoney1.add(BigDecimal.valueOf(account1.getTodayProfit())).doubleValue());
							//integral   积分
//		                        account1.setIntegral(integral1.add(BigDecimal.valueOf(account1.getIntegral())).doubleValue());
							accountMapper.update(account1);
							//插入收益记录
							DynamicRecord dynamicRecord1 = new DynamicRecord();
							dynamicRecord1.setId(IdGen.uuid());
							dynamicRecord1.setFrommem(member);
							dynamicRecord1.setMember(upMem);
							dynamicRecord1.setMoney(recordMoney1.doubleValue());
							dynamicRecord1.setName("推荐奖(间推)");
							dynamicRecord1.preInsert();
							dynamicRecordMapper.insert(dynamicRecord1);
						}

					}
				}
			}
		}
	}


	/**
	 * 微信回调参团
	 * @param openid
	 * @param orderNo
	 */
	@Transactional(readOnly = false)
	public void backGroup(String openid, String orderNo) {
		List<Member> memberList = memberMapper.findByOpenid(openid);
		if (memberList.size()>0){
			for (Member member : memberList) {
				if (member != null){
					WxGroup wxGroup = new WxGroup();
					wxGroup.setOrderNo(orderNo);
					wxGroup.setMemberId(member.getId());
					List<WxGroup> list = wxGroupMapper.findList(wxGroup);
					if (list.size()>0){
						for (WxGroup group : list) {
							if ("123".equals(group.getSessionsId())){
								//普通订单支付
								OrdersStore ordersStore = ordersStoreService.getByNo(orderNo);
								if ("1".equals(ordersStore.getOrdersStatus())){
									ordersStore.setOrdersStatus("2");
									ordersStore.setMoney(group.getCost());
									ordersStore.setPaytime(new Date());
									ordersStoreService.save(ordersStore);

									//记录
//									DynamicRecord dynamicRecord = new DynamicRecord();
//									dynamicRecord.setMember(member);
//									dynamicRecord.setFrommem(member);
//									dynamicRecord.setName("积分购物");
//									dynamicRecord.setMoney(ordersStore.getJifen());
//									dynamicRecordService.save(dynamicRecord);
								}
							}else if ("recharge".equals(group.getSessionsId())){
								Recharge recharge = new Recharge();
								recharge.setRechargePic(orderNo);
								recharge.setMemberId(group.getMemberId());
								List<Recharge> recharges = rechargeService.findList(recharge);
								if (recharges.size()>0){
									for (Recharge recharge1 : recharges) {
										if ("0".equals(recharge1.getRechargeStatus())){
											recharge1.setRechargeStatus("1");

											Member member1 = memberMapper.get(recharge1.getMemberId());
											if (member1 != null){
												Account account = accountMapper.get(member1.getAccount().getId());
												if (account != null){
													BigDecimal yue = BigDecimal.valueOf(account.getYue()).add(BigDecimal.valueOf(recharge1.getRechargeMoney()));
													account.setYue(yue.doubleValue());
													account.preUpdate();
													accountMapper.update(account);
												}
											}
											rechargeService.save(recharge1);

										}
									}
								}
							} else {
								//开团之前的最新记录
								GroupRecord latestRecord = groupRecordMapper.findLatestRecord(group.getSessionsId());
								//查询场次
								Sessions sessions = sessionsMapper.get(group.getSessionsId());
								//场次参与金额
								BigDecimal money = BigDecimal.valueOf(sessions.getSessionsPrice());
								if (latestRecord == null){
									//首次拼团，创建第一期记录
									GroupRecord groupRecord = new GroupRecord();
									groupRecord.setId(IdGen.uuid());
									groupRecord.setPercentNo(1);
									groupRecord.setSessions(sessions);
									groupRecord.setIsEnd("0");
									groupRecord.setOrderNo(orderNo);
									groupRecord.setPrizeStatus("0");
									groupRecord.setGroupStatus("0");
									groupRecord.preInsert();
									groupRecordMapper.insert(groupRecord);
									//扣除能量值  -1
									PartitionInfo partitionInfo = new PartitionInfo();
									partitionInfo.setMember(member);
									partitionInfo.setSessions(sessions);
									List<PartitionInfo> partitionInfoList = partitionInfoMapper.findList(partitionInfo);
									if (partitionInfoList.size() > 0){
										partitionInfoList.get(0).setEnergyValue(partitionInfoList.get(0).getEnergyValue()-1);
										partitionInfoList.get(0).preUpdate();
										partitionInfoMapper.update(partitionInfoList.get(0));
									}
									//购买拼团订单
									GroupOrders groupOrders = new GroupOrders();
									groupOrders.setGroupRecord(groupRecord);
									groupOrders.setMember(member);
									groupOrders.setOrderNo(orderNo);
									groupOrders.setMoney(money.doubleValue());
									//未开奖
									groupOrders.setOrderStatus("0");
									save(groupOrders);
									System.out.println("参与成功,请等待拼团成功后开奖。");
								}else {
									//查询当前场次所有未成团记录
									GroupRecord entity = new GroupRecord();
									entity.setSessions(sessions);
//									entity.setGroupStatus("0");
//									entity.setIsEnd("0");
									List<GroupRecord> nonList = groupRecordMapper.findNonList(entity);
									//记录扫描过得未成团记录
									List<GroupRecord> scanList = new ArrayList<>();
									if (nonList.size()>0){
										for (GroupRecord groupRecord : nonList) {
											GroupOrders selectOrders = new GroupOrders();
											selectOrders.setGroupRecord(groupRecord);
											List<GroupOrders> sList = findList(selectOrders);
											if (sList.stream().anyMatch(groupOrders -> groupOrders.getMember().getId().equals(member.getId()))){
												scanList.add(groupRecord);
												continue;
											}else {
												//扣除能量值  -1
												PartitionInfo partitionInfo = new PartitionInfo();
												partitionInfo.setMember(member);
												partitionInfo.setSessions(sessions);
												List<PartitionInfo> partitionInfoList = partitionInfoMapper.findList(partitionInfo);
												if (partitionInfoList.size() > 0){
													partitionInfoList.get(0).setEnergyValue(partitionInfoList.get(0).getEnergyValue()-1);
													partitionInfoList.get(0).preUpdate();
													partitionInfoMapper.update(partitionInfoList.get(0));
												}
												//购买拼团订单
												GroupOrders groupOrders = new GroupOrders();
												groupOrders.setGroupRecord(groupRecord);
												groupOrders.setMember(member);
												groupOrders.setOrderNo(groupRecord.getOrderNo());
												//未开奖
												groupOrders.setOrderStatus("0");
												groupOrders.setMoney(money.doubleValue());
												save(groupOrders);
												//成团
												if (sList.size()+1 == sessions.getSessionsMember()){
													//成团
													groupRecord.setGroupStatus("1");
													groupRecord.setGroupDate(new Date());
													groupRecord.preUpdate();
													groupRecordMapper.update(groupRecord);
													//开奖
													drawPrize(groupRecord);
												}
												System.out.println("参与成功,请等待拼团成功后开奖。");
												break;
											}
										}
										//未成团记录全部扫描完，若用户都已参与，让用户开启一个新的团
										if (scanList.size() == nonList.size()){
											//   创建新一期的拼团记录
											GroupRecord groupRecord = new GroupRecord();
											groupRecord.setId(IdGen.uuid());
											groupRecord.setPercentNo(latestRecord.getPercentNo()+1);
											groupRecord.setSessions(sessions);
											groupRecord.setIsEnd("0");
											groupRecord.setOrderNo(orderNo);
											groupRecord.setPrizeStatus("0");
											groupRecord.setGroupStatus("0");
											groupRecord.preInsert();
											groupRecordMapper.insert(groupRecord);
											//扣除能量值  -1
											PartitionInfo partitionInfo = new PartitionInfo();
											partitionInfo.setMember(member);
											partitionInfo.setSessions(sessions);
											List<PartitionInfo> partitionInfoList = partitionInfoMapper.findList(partitionInfo);
											if (partitionInfoList.size() > 0){
												partitionInfoList.get(0).setEnergyValue(partitionInfoList.get(0).getEnergyValue()-1);
												partitionInfoList.get(0).preUpdate();
												partitionInfoMapper.update(partitionInfoList.get(0));
											}
											//购买拼团订单
											GroupOrders groupOrders = new GroupOrders();
											groupOrders.setGroupRecord(groupRecord);
											groupOrders.setMember(member);
											groupOrders.setOrderNo(orderNo);
											//未开奖
											groupOrders.setOrderStatus("0");
											groupOrders.setMoney(money.doubleValue());
											save(groupOrders);
											System.out.println("参与成功,请等待拼团成功后开奖。");
										}
									}else {
										//已成团   创建新一期的拼团记录
										GroupRecord groupRecord = new GroupRecord();
										groupRecord.setId(IdGen.uuid());
										groupRecord.setPercentNo(latestRecord.getPercentNo()+1);
										groupRecord.setSessions(sessions);
										groupRecord.setIsEnd("0");
										groupRecord.setOrderNo(orderNo);
										groupRecord.setPrizeStatus("0");
										groupRecord.setGroupStatus("0");
										groupRecord.preInsert();
										groupRecordMapper.insert(groupRecord);
										//扣除能量值  -1
										PartitionInfo partitionInfo = new PartitionInfo();
										partitionInfo.setMember(member);
										partitionInfo.setSessions(sessions);
										List<PartitionInfo> partitionInfoList = partitionInfoMapper.findList(partitionInfo);
										if (partitionInfoList.size() > 0){
											partitionInfoList.get(0).setEnergyValue(partitionInfoList.get(0).getEnergyValue()-1);
											partitionInfoList.get(0).preUpdate();
											partitionInfoMapper.update(partitionInfoList.get(0));
										}
										//购买拼团订单
										GroupOrders groupOrders = new GroupOrders();
										groupOrders.setGroupRecord(groupRecord);
										groupOrders.setMember(member);
										groupOrders.setOrderNo(orderNo);
										//未开奖
										groupOrders.setOrderStatus("0");
										groupOrders.setMoney(money.doubleValue());
										save(groupOrders);
										System.out.println("参与成功,请等待拼团成功后开奖。");
									}
								}
							}

							wxGroupMapper.deleteByLogic(group);
						}
					}
				}
			}
		}

	}


	/**
	 * 发放团队奖
	 */
	@Transactional(readOnly = false)
	public void awardTeamAward(Member member,BigDecimal money){
		int flag1 = 0;
		int flag2 = 0;
		int flag3 = 0;
		String name = "";
		//极差发放奖励
		Double m = 0.00;
		//平级应得奖励
		Double pm = 0.00;
		Double pm1 = 0.00;
		Double pm2 = 0.00;
		boolean isSend = false;
		Double tm = 0.00;
		if (member.getP() != null){
			Member upMember = memberMapper.get(member.getP().getId());
			while (upMember != null && !"admin".equals(upMember.getLoginName())){
				GroupOrders groupOrders = new GroupOrders();
				groupOrders.setMember(upMember);
				List<GroupOrders> ordersList = findList(groupOrders);
				if (ordersList.size()>0){
					Account account = accountMapper.get(upMember.getAccount().getId());
					//2%
					if (upMember.getNum()>=3&&upMember.getNum()<6){
						if (flag1 == 0 && flag2 == 0 && flag3 == 0){
							logger.debug("flag1================"+flag1+"num========"+upMember.getNum()+"发放用户："+upMember.getLoginName());
							name="团队奖1";
							m=money.multiply(BigDecimal.valueOf(0.02)).doubleValue();
							account.setYue(account.getYue()+m);
							//dynamicProfit   总动态收益
							account.setDynamicProfit(account.getDynamicProfit()+m);
							//todayDynamic    今日动态收益
							account.setTodayDynamic(account.getTodayDynamic()+m);
							//totalProfit     总收益
							account.setTotalProfit(account.getTotalProfit()+m);
							//todayProfit     今日总收益
							account.setTodayProfit(account.getTodayProfit()+m);
							tm = m;
							flag1 = 1;
							isSend = true;
						}else if (flag1 == 1 && flag2 == 0 && flag3 == 0){
							logger.debug("flag1================"+flag1+"num========"+upMember.getNum()+"发放用户："+upMember.getLoginName());
							name="团队奖1";
							pm=BigDecimal.valueOf(m).multiply(BigDecimal.valueOf(0.2)).doubleValue();
							account.setYue(account.getYue()+pm);
							//dynamicProfit   总动态收益
							account.setDynamicProfit(account.getDynamicProfit()+pm);
							//todayDynamic    今日动态收益
							account.setTodayDynamic(account.getTodayDynamic()+pm);
							//totalProfit     总收益
							account.setTotalProfit(account.getTotalProfit()+pm);
							//todayProfit     今日总收益
							account.setTodayProfit(account.getTodayProfit()+pm);
							tm = pm;
							flag1 = 2;
							isSend = true;
						}else {
							isSend = false;
						}
					}else if (upMember.getNum()>=6&&upMember.getNum()<9){
						if (flag2 == 0 && flag3 == 0){
							logger.debug("flag2================"+flag2+"num========"+upMember.getNum()+"发放用户："+upMember.getLoginName());
							name="团队奖2";
							m=money.multiply(BigDecimal.valueOf(0.03)).doubleValue()-m;
							account.setYue(account.getYue()+m);
							//dynamicProfit   总动态收益
							account.setDynamicProfit(account.getDynamicProfit()+m);
							//todayDynamic    今日动态收益
							account.setTodayDynamic(account.getTodayDynamic()+m);
							//totalProfit     总收益
							account.setTotalProfit(account.getTotalProfit()+m);
							//todayProfit     今日总收益
							account.setTodayProfit(account.getTodayProfit()+m);
							tm = m;
							flag2 = 1;
							isSend = true;
						}else if (flag2 == 1 && flag3 == 0){
							logger.debug("flag2================"+flag2+"num========"+upMember.getNum()+"发放用户："+upMember.getLoginName());
							name="团队奖2";
							pm1=BigDecimal.valueOf(m).multiply(BigDecimal.valueOf(0.2)).doubleValue();
							account.setYue(account.getYue()+m);
							//dynamicProfit   总动态收益
							account.setDynamicProfit(account.getDynamicProfit()+pm1);
							//todayDynamic    今日动态收益
							account.setTodayDynamic(account.getTodayDynamic()+pm1);
							//totalProfit     总收益
							account.setTotalProfit(account.getTotalProfit()+pm1);
							//todayProfit     今日总收益
							account.setTodayProfit(account.getTodayProfit()+pm1);
							tm = pm1;
							flag2 = 2;
							isSend = true;
						}else {
							isSend = false;
						}
					}else if (upMember.getNum()>=9){
						if (flag3 == 0){
							logger.debug("flag3================"+flag3+"num========"+upMember.getNum()+"发放用户："+upMember.getLoginName());
							name="团队奖3";
							m=money.multiply(BigDecimal.valueOf(0.04)).doubleValue()-m;
							account.setYue(account.getYue()+m);
							//dynamicProfit   总动态收益
							account.setDynamicProfit(account.getDynamicProfit()+m);
							//todayDynamic    今日动态收益
							account.setTodayDynamic(account.getTodayDynamic()+m);
							//totalProfit     总收益
							account.setTotalProfit(account.getTotalProfit()+m);
							//todayProfit     今日总收益
							account.setTodayProfit(account.getTodayProfit()+m);
							tm = m;
							flag3 = 1;
							isSend = true;
						}else if (flag3 == 1){
							logger.debug("flag3================"+flag3+"num========"+upMember.getNum()+"发放用户："+upMember.getLoginName());
							name="团队奖3";
							pm2=BigDecimal.valueOf(m).multiply(BigDecimal.valueOf(0.2)).doubleValue();
							account.setYue(account.getYue()+pm2);
							//dynamicProfit   总动态收益
							account.setDynamicProfit(account.getDynamicProfit()+pm2);
							//todayDynamic    今日动态收益
							account.setTodayDynamic(account.getTodayDynamic()+pm2);
							//totalProfit     总收益
							account.setTotalProfit(account.getTotalProfit()+pm2);
							//todayProfit     今日总收益
							account.setTodayProfit(account.getTodayProfit()+pm2);
							tm = pm2;
							flag3 = 2;
							isSend = true;
						}else {
							isSend = false;
						}
					}else {
						isSend = false;
					}
					if (isSend){
						//插入收益记录
						DynamicRecord dynamicRecord = new DynamicRecord();
						dynamicRecord.setId(IdGen.uuid());
						dynamicRecord.setFrommem(member);
						dynamicRecord.setMember(upMember);
						dynamicRecord.setMoney(tm);
						dynamicRecord.setName(name);
						dynamicRecord.setIsNewRecord(true);
						dynamicRecord.preInsert();
						dynamicRecordMapper.insert(dynamicRecord);
						accountMapper.update(account);
					}

				}
				if (upMember.getP() != null){
					upMember = memberMapper.get(upMember.getP().getId());
				}else {
					break;
				}
			}

		}
	}

}